package com.zlz.blog.server.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.zlz.blog.manage.common.entity.oauth.LoginResult;
import com.zlz.blog.manage.common.entity.oauth.LoginUser;
import com.zlz.blog.manage.common.entity.oauth.SysPermission;
import com.zlz.blog.manage.common.response.ResultSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhulinzhong
 * @version 1.0 CreateTime:2020-05-19 11:14
 * @description token解析
 */
@Slf4j
@Component
public class LoginUtil {

    private static final String OAUTH_HEADER = "Authorization";
    private static final String OAUTH_HEADER_SPLIT = " ";
    public static final Integer OUT_TIME = 30 * 60;
    public static final String SESSION_USER = "user";

    @Value("{token.key}")
    private String key;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成token
     *
     * @param userId
     * @return
     */
    public String generateToken(Long userId) {
        return JWT.create()
                //设置过期时间
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                //设置接受方信息，一般时登录用户
                .withClaim("user", userId)
                .sign(Algorithm.HMAC256(this.key));
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        try {
            // 检查session
            Object attribute = request.getSession().getAttribute(SESSION_USER);
            if (attribute != null) {
                return new JSONObject(attribute).toBean(LoginUser.class);
            }
            // 检查header
            String authorization = request.getHeader(OAUTH_HEADER);
            String token = authorization.split(OAUTH_HEADER_SPLIT)[1];
            String userInfo = stringRedisTemplate.opsForValue().get(OAUTH_HEADER + ":" + token);
            return new JSONObject(userInfo).toBean(LoginUser.class);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public LoginUser getLoginUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return getLoginUser(request);
    }

    /**
     * 检查是否登录
     *
     * @param request HttpServletRequest
     * @return
     */
    public ResultSet<Boolean> checkLogin(HttpServletRequest request) {
        try {
            String user = (String) request.getSession().getAttribute(OAUTH_HEADER);
            if (user != null) {
                return ResultSet.success();
            }
            String authorization = request.getHeader(OAUTH_HEADER);
            String token = authorization.split(OAUTH_HEADER_SPLIT)[1];
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(this.key)).build();
            jwtVerifier.verify(token);
            String userInfo = stringRedisTemplate.opsForValue().get(OAUTH_HEADER + ":" + token);
            if (StringUtils.isEmpty(userInfo)) {
                return ResultSet.loginError("获取登录用户失败，请重新登录");
            }
            return ResultSet.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultSet.loginError("获取登录用户失败，请重新登录");
        }
    }

    /**
     * 检查权限是否符合
     *
     * @param url 请求路径
     * @return
     */
    public ResultSet<Boolean> checkAuthorization(String url) {
        String permissions = stringRedisTemplate.opsForValue().get("PERMISSIONS");
        List<SysPermission> sysPermissions = new JSONArray(permissions).toList(SysPermission.class);
        if (CollectionUtils.isEmpty(sysPermissions)) {
            return ResultSet.error();
        }
        List<SysPermission> allowPermissions = sysPermissions.stream().filter(sysPermission -> contains(sysPermission.getUrl(), url)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(allowPermissions)){
            return ResultSet.unauthorizedError("该路径未定义权限，请联系管理员定义权限！");
        }
        LoginUser loginUser = getLoginUser();
        List<SysPermission> userPermissions = new ArrayList<>();
        loginUser.getSysRoles().forEach(role -> userPermissions.addAll(role.getSysPermissions()));
        Map<String, SysPermission> permissionIdMap = userPermissions.stream().collect(Collectors.toMap(SysPermission::getEname, Function.identity()));
        StringBuilder sb = new StringBuilder();
        sb.append("访问该路径需要拥有（ ");
        for (int i = 0; i < allowPermissions.size(); i++) {
            if (permissionIdMap.get(allowPermissions.get(i).getEname()) != null) {
                return ResultSet.success();
            }
            if (i == allowPermissions.size() - 1) {
                sb.append(allowPermissions.get(i).getEname()).append(" ）中的任一权限！");
            } else {
                sb.append(allowPermissions.get(i).getEname()).append("，");
            }
        }
        return ResultSet.unauthorizedError(sb.toString());
    }

    /**
     * 路由与权限资源匹配检查
     *
     * @param uri
     * @return
     */
    public boolean checkPath(String uri) {
        String whitelistJson = stringRedisTemplate.opsForValue().get("WHITELIST");
        List<String> paths = new JSONArray(whitelistJson).toList(String.class);
        if (CollectionUtils.isEmpty(paths)) {
            return false;
        }
        if (paths.isEmpty() || StringUtils.isEmpty(uri)) {
            return false;
        }
        for (String pPath : paths) {
            if (contains(pPath, uri)) {
                return true;
            }
        }
        return false;
    }

    private boolean contains(String pPath, String uri) {
        if ("/**".equals(pPath) || pPath.equals(uri)) {
            return true;
        }
        // 将路由地址拆分，逐级匹配，若是全部匹配成功则返回成功，否则返回失败
        boolean matching = true;
        String[] pps = pPath.split("/");
        String[] us = uri.split("/");
        // uri的级数小于权限路由的级数 p:"/test" pp:"/test/1"
        boolean isBreak1 = pps.length > us.length;
        // 权限路由的最后一级不是模糊匹配，并且uri与权限路由的长度不同，直接结束本次匹配
        boolean isBreak2 = !"**".equals(pps[pps.length - 1]) && pps.length != us.length;
        if (isBreak1 || isBreak2) {
            return false;
        }
        for (int i = 0; i < us.length; i++) {
            // 匹配到/** 直接返回验证成功，不再需要检验之后的路由地址
            if ("**".equals(pps[i])) {
                return true;
            }
            // 匹配到/* 本次检验直接返回验证成功，继续进行之后的检验
            if ("*".equals(pps[i])) {
                matching = true;
                continue;
            }
            // 出现不匹配路由地址的直接结束判断
            matching = pps[i].equals(us[i]);
            if (!matching) {
                break;
            }
        }
        if (matching) {
            return true;
        }
        return false;
    }

    /**
     * 设置登录信息
     *
     * @param request
     * @param user
     * @return
     */
    public LoginResult setSession(HttpServletRequest request, LoginUser user) {
        LoginResult token = LoginResult.builder()
                .token(this.generateToken(user.getId()))
                .loginUser(user)
                .build();
        user.setPassword(null);
        user.setSalt(null);
        String userInfo = new JSONObject(user).toString();
        request.getSession().setAttribute(SESSION_USER, userInfo);
        request.getSession().setAttribute(OAUTH_HEADER, token.getToken());
        request.getSession().setMaxInactiveInterval(OUT_TIME);
        stringRedisTemplate.opsForValue().set(OAUTH_HEADER + ":" + token.getToken(), userInfo, OUT_TIME, TimeUnit.SECONDS);
        return token;
    }

    /**
     * 刷新超时时间
     *
     * @param request
     */
    public void refresh(HttpServletRequest request) {
        request.getSession().setMaxInactiveInterval(OUT_TIME);
        stringRedisTemplate.expire(OAUTH_HEADER, OUT_TIME, TimeUnit.SECONDS);
    }

    /**
     * 退出登录
     *
     * @param request
     */
    public void logout(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(OAUTH_HEADER);
        request.getSession().removeAttribute(OAUTH_HEADER);
        request.getSession().removeAttribute(SESSION_USER);
        stringRedisTemplate.delete(OAUTH_HEADER + ":" + (String) attribute);
    }
}
